var express = require('express');
var router = express.Router();
var db = require('../mysql/db')
const { jwtCheck } = require('../utils/jwt')


// let sql = 'SELECT * FROM PayInfo order by registerDate desc';
// let str = '';
// db.query(sql, [], results => {
    
// console.log(results)
// })
router.get('/get', jwtCheck, function (req, res, next) {
    let sql = 'SELECT * FROM pay_info order by registerDate desc';
    db.query(sql, [], results => {
        res.json({
            errno: 0, message: results
        })
        //console.log(results)
    })
});

router.post('/set', function (req, res, next) {
    const payInfo = req.body
    let sql = "UPDATE pay_info SET isPay = 1, payCost = 0 WHERE registerId = " + payInfo.registerId;
    db.query(sql, [], results => {
        res.json({
            errno: 0, message: results
        })
        //console.log(results)
    })
});

router.post('/new', function (req, res, next) {
    const PayInfo = req.body
    const payInfo = PayInfo.medicineList.concat(PayInfo.checkProjectList)
    console.log(PayInfo)
    var payCost = 0;
    payInfo.forEach(item => {
        payCost = payCost + item.total 
    });

    let sql = 'INSERT INTO pay_info(registerId, selfName, selfId, doctorName, doctorId, registerDate, payInfo, isPay, payCost) values (?, ?, ?, ?, ?, ?, ?, ?, ?)';
    db.query(sql, [PayInfo.register_id, PayInfo.self_name, PayInfo.self_id, PayInfo.doctor_name, PayInfo.doctor_id, PayInfo.register_date, JSON.stringify(payInfo), 0, payCost], (err, results) => {
        res.json({
            errno: 0, message: results
        })
    })
});

router.post('/select', function (req, res, next) {
    //console.log(req.body.registerId)
    let sql = "SELECT * FROM pay_info WHERE registerId =" + req.body.registerId;
    let str = '';
    db.query(sql, [], results => {
        res.json({
            errno: 0, message: results
        })
        //console.log(results)
    })
});

module.exports = router;
